<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class ShopCrowd extends Model
{
    protected $table = 'shop_crowds';

    public function transform_my_join_list()
    {
        $shop = $this->shop;
        if ($shop) {
            $img_arr = [];
            if (is_array($shop->shop_info)) {
                foreach ($shop->shop_info as $value) {
                    $img_arr[] = config('app.img_url') . $value;
                }
            }
            $shop_browse = ShopBrowse::where('shop_id',$this->shop_id)->get();
            if (count($shop_browse) > 4) {
                $crowds = $shop_browse->random(4)->pluck('user_id');
            } else {
                $crowds = $shop_browse->pluck('user_id');
            }
            $user_avatar = User::whereIn('id', $crowds)->get(['id as user_id', 'avatar'])->each(function ($img) {
                $img->avatar = $img->avatar;
            });

            return [
                'id' => $shop->id,
                'shop_type' => $shop->shop_type,
                'shop_info' => $img_arr,
                'shop_price' => $shop->shop_price,
                'has_crowd' => $this->where('shop_id', $shop->id)->sum('money'),
                'address' => $shop->address,
                'rest_time' => timediff(time(), $shop->crowd_funding_end),
                'user_avatar' => $user_avatar
            ];
        }
    }

    public function shop()
    {
        return $this->belongsTo(Shop::class, 'shop_id', 'id');
    }

}
